<?php

require "Minifier.php";
require "Chinese.php";

/*
  处理所有文件的通用函数
  $from_path: 要遍历的目录
  $to_path: 目标目录，会与源目录下文件的相对路径一起拼起来作为参数传给$process_func
  $condition: 条件函数，传入参数是遍历目录下的每一个fileInfo，返回值如果为true，则执行$process_func
  $process_func: 处理函数，传入源文件和目标文件
 */
function process_all_files_with_condition($from_path, $to_path, $condition, $process_func)
{
    $dir = new DirectoryIterator($from_path);
    foreach ($dir as $fi) {
        if (!$fi->isDot()) {
            $filename = $fi->getFilename();
            if ($fi->isDir()) {
                process_all_files_with_condition(join_paths($from_path, $filename), join_paths($to_path, $filename), $condition, $process_func);
            } else {
                if ($condition($fi)) {
                    $process_func(join_paths($from_path, $filename), join_paths($to_path, $filename));
                }
            }
        }
    }
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// 以下函数用于php文件去注释

function php_file_condition($fi)
{
    return strtolower($fi->getExtension()) == 'php';
}

function strip_php_comment($str)
{
    $newStr = '';

    $commentTokens = array(T_COMMENT);

    if (defined('T_DOC_COMMENT')) {
        $commentTokens[] = T_DOC_COMMENT;
    }
    if (defined('T_ML_COMMENT')) {
        $commentTokens[] = T_ML_COMMENT;
    }

    $tokens = token_get_all($str);

    foreach ($tokens as $token) {
        if (is_array($token)) {
            if (in_array($token[0], $commentTokens)) {
                // 包含[Discuz!]和[UCenter]的是版权注释，不去掉
                if (strpos($token[1], '[Discuz!]') || strpos($token[1], '[UCenter]')) {
                    $newStr .= $token[1];
                }
                // 单行注释去掉后，后面加回车，避免把两行弄到一起
                if (substr($token[1], 0, 2) != "/*") {
                    $newStr .= "\n";
                }
                continue;
            }
            $token = $token[1];
        }
        $newStr .= $token;
    }
    return $newStr;
}

function strip_one_php_file($from_file, $to_file)
{
    $should_strip = true;

    // config文件中的注释不去掉
    if (ends_with($from_file, 'config_global_default.php')) $should_strip = false;
    if (ends_with($from_file, 'config_ucenter_default.php')) $should_strip = false;

    $buffer = file_get_contents($from_file);
    if ($should_strip) $buffer = strip_php_comment($buffer);

    mkdir_of_file($to_file);
    file_put_contents($to_file, $buffer);
}

function strip_all_php_files($from_path, $to_path)
{
    logging\info("正在处理PHP文件");
    process_all_files_with_condition($from_path, $to_path, 'php_file_condition', 'strip_one_php_file');
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// 以下三个函数用于js文件去注释、去空格、回车

function strip_one_js_file($from_file, $to_file)
{
    $buffer = file_get_contents($from_file);
    // already minified files, skip them
    $to_skip = array('.min.js', 'highcharts.js', 'qqapi.custom.js', '/qb.js', 'jpeg.encoder.basic.js', 'userapp_swfobject.js');
    $to_minify = true;

    foreach ($to_skip as $skip) {
        if (ends_with($from_file, $skip)) {
            logging\debug("直接复制JavaScript文件 %s", $from_file);
            $to_minify = false;
            break;
        }
    }

    if ($to_minify) {
        $buffer = JShrink\Minifier::minify($buffer);
    }

    mkdir_of_file($to_file);
    file_put_contents($to_file, $buffer);
}

function js_file_condition($fi)
{
    return strtolower($fi->getExtension()) == 'js';
}

function strip_all_js_files($from_path, $to_path)
{
    logging\info("正在处理JavaScript文件");
    process_all_files_with_condition($from_path, $to_path, 'js_file_condition', 'strip_one_js_file');
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// 复制一个文件，工具函数
function copy_file($from_file, $to_file)
{
    mkdir_of_file($to_file);
    copy($from_file, $to_file);
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// 复制所有非js, 非php文件
function copy_all_other_files($from_path, $to_path)
{
    logging\info("正在复制其它文件");
    process_all_files_with_condition($from_path, $to_path,
        function ($fi) {
            $ext = strtolower($fi->getExtension());
            return !in_array($ext, array('js', 'php'));
        }, 'copy_file');
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// 复制所有文件
function copy_all_files($from_path, $to_path)
{
    logging\info("正在按目录结构复制文件：%s -> %s", $from_path, $to_path);
    process_all_files_with_condition($from_path, $to_path,
        function ($fi) {
            return true;
        }, 'copy_file');
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// 以下两个函数用于原地转编码，源编码固定为UTF8
function encoding_condition($fi)
{
    if (strpos($fi->getPath(), "/template/default/m/")) {
        return false;
    }
    if (ends_with($fi->getFilename(), 'lang_swfupload.php')) {
        return false;
    }

    $ext = strtolower($fi->getExtension());
    if (in_array($ext, array('css', 'js', 'php', 'xml', 'htm', 'ini', 'txt', 'sql'))) {
        return true;
    }
    return false;
}

function convert_encoding_in($from_path, $to_encoding)
{
    logging\info("转换编码到 %s: ", $to_encoding, $from_path);
    process_all_files_with_condition($from_path, $from_path,
        'encoding_condition', 
        function ($from_file, $to_file) use (&$to_encoding) {
            // logging\info("正在转换编码为 %s：%s -> %s", $to_encoding, $from_file, $to_file);
            $buffer = file_get_contents($from_file);
            $buffer = mb_convert_encoding($buffer, $to_encoding, "UTF-8");
            file_put_contents($to_file, $buffer);
        }
    );
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// 以下函数用于转换语言到繁体

$chinese = new SteelyWing\Chinese\Chinese();

function convert_to_zh_hant($from_path)
{
    global $chinese;

    logging\info("转换语言到繁体：%s", $from_path);
    process_all_files_with_condition($from_path, $from_path,
        function ($fi) {
            $ext = strtolower($fi->getExtension());
            return in_array($ext, array('css', 'js', 'php', 'xml', 'htm', 'ini', 'txt', 'sql'));
        }, 
        function ($from_file, $to_file) use (&$chinese) {
            $buffer = file_get_contents($from_file);
            $buffer = $chinese->to(SteelyWing\Chinese\Chinese::ZH_HANT, $buffer);
            file_put_contents($to_file, $buffer);
        }
    );    
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
// css 替换 Simsun为mingliu

function css_replace_simsun_with_mingliu($from_path)
{
    logging\info("CSS替换字体：%s", $from_path);
    process_all_files_with_condition($from_path, $from_path,
        function ($fi) {
            $ext = strtolower($fi->getExtension());
            return in_array($ext, array('css'));
        }, 
        function ($from_file, $to_file) use (&$chinese) {
            $buffer = file_get_contents($from_file);
            $buffer = str_replace('Simsun', 'mingliu', $buffer);
            $buffer = str_replace('simsun', 'mingliu', $buffer);
            file_put_contents($to_file, $buffer);
        }
    );    
}